﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using WPF_DbCenter.CommonMethod;
using System.Diagnostics;
using System.Data.Common;
using System.Data;
using XLCS.Common;
using System.ComponentModel;
using Xceed.Wpf.DataGrid;

namespace WPF_DbCenter.UI
{
    public partial class Main 
    {
        public enum CurCommandType
        {
            SpeicalCommand,
            Query,
            Insert,
            Update,
            Delete,
            SystemAction,
            CreateTable,
            Unknown,
        }

        public CurCommandType _curCmdType { get; set; }

        /// <summary>
        /// Do command collection 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void butQueryClick(object sender, RoutedEventArgs e)
        {
            
            if (string.IsNullOrEmpty(txtMainCmd.Text))
            {
                MessageBox.Show("Please input the query command first");
                return;
            }
            string cmdText=ParseCmd(txtMainCmd.Text);

            CmdHistoryList.Add(cmdText);

            DbCommand cmd = App.MainEngineer.DbHandler.GetSqlStringCommand(cmdText);
            switch (_curCmdType)
            {
                case CurCommandType.Query:

                    Do_SelectCmd(cmd);

                    break;
                case CurCommandType.Update:

                    Do_UpdateCmd(cmd);

                    break;
                case CurCommandType.Delete:

                    Do_DeleteCmd(cmd);

                    break;
                case CurCommandType.Insert:

                    Do_InsertCmd(cmd);

                    break;
                case CurCommandType.SystemAction:

                    Do_SysCmd(cmd);

                    break;
                case CurCommandType.SpeicalCommand:
                    Do_SpeicalCmd(cmd);
                    break;
                case CurCommandType.CreateTable:

                    Do_CreateTableCmd(cmd);

                    break;
                case CurCommandType.Unknown:

                    ProcessException.DisplayErrors(new Exception("Not valid command"));

                    break;
                default:
                    Do_SelectCmd(cmd);
                    break;
            }

            txtMainCmd.Text = string.Empty;

        }

        private void Do_CreateTableCmd(DbCommand cmd)
        {
            try
            {
                int resultCount = App.MainEngineer.DbHandler.ExecuteNonQuery(cmd);
                if (resultCount == -1)
                {
                    MessageBox.Show(String.Format("Table {0} has created ", 1));
                    RefreshCurrentDbStatus();
                }
                else
                {
                    MessageBox.Show(String.Format("Table has failure"));
                }
            }
            catch (Exception ee)
            {
                ProcessException.DisplayErrors(ee);
            }
        }

        private void Do_InsertCmd(DbCommand cmd)
        {
            try
            {
            int resultCount=App.MainEngineer.DbHandler.ExecuteNonQuery(cmd);

            MessageBox.Show(String.Format("{0} has changed ", resultCount));
            }
            catch (Exception ee)
            {
                ProcessException.DisplayErrors(ee);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="cmd"></param>
        private void Do_SpeicalCmd(DbCommand cmd)
        {
            try
            {
                object result = App.MainEngineer.DbHandler.ExecuteNonQuery(cmd);
            }
            catch (Exception ee)
            {
                ProcessException.DisplayErrors(ee);
            }
            RefreshCurrentDbStatus();
        }


        private void Do_SysCmd(DbCommand cmd)
        {
            try
            {
                object result=App.MainEngineer.DbHandler.ExecuteScalar(cmd);
                MessageBox.Show(String.Format("{0} has changed ", result));
            }
            catch (Exception ee)
            {
                ProcessException.DisplayErrors(ee);
            }
            RefreshCurrentDbStatus();
        }

        private void RefreshCurrentDbStatus()
        {

            if (App.MainEngineer.GetTableList()!=null)
            {
                Main_Loaded(null, null);
            }
            else
            {
                throw new Exception("System Query Error");
            }
        }

        private void Do_DeleteCmd(DbCommand cmd)
        {
            try
            {
                object result = App.MainEngineer.DbHandler.ExecuteScalar(cmd);
                MessageBox.Show(String.Format("{0} has changed ", result));

            }
            catch (Exception ee)
            {
                ProcessException.DisplayErrors(ee);
            }

        }

        private void Do_UpdateCmd(DbCommand cmd)
        {
            try
            {
                object result = App.MainEngineer.DbHandler.ExecuteScalar(cmd);
                MessageBox.Show(String.Format("{0} has changed ", result));

            }
            catch (Exception ee)
            {
                ProcessException.DisplayErrors(ee);
            }

        }

        private void Do_SelectCmd(DbCommand cmd)
        {
            try
            {
                StartProcessingBar();
                DataSet ds = App.MainEngineer.DbHandler.ExecuteDataSet(cmd);

                FillUI(ds);
                
            }
            catch (Exception ee)
            {
                ProcessException.DisplayErrors(ee);
            }
            finally
            {

                StopProcessingBar();
            }
        }

        private void FillUI(DataSet ds)
        {

            // Clear the grid.
            dataGridControl1.ClearValue(DataGridControl.ItemsSourceProperty);
            dataGridControl1.Items.Clear();
            dataGridControl1.Items.SortDescriptions.Clear();
            dataGridControl1.Items.GroupDescriptions.Clear();
            dataGridControl1.Columns.Clear();

            DataGridCollectionView dataGridCollectionView = new DataGridCollectionView(ds.Tables[0].DefaultView);
            this.dataGridControl1.ItemsSource = dataGridCollectionView;

        }
        /// <summary>
        /// parse sql command ,and type
        /// </summary>
        /// <param name="cmdText"></param>
        /// <returns></returns>
        private string ParseCmd(string cmdText)
        {
            
            string result = string.Empty;
            if (string.IsNullOrEmpty(cmdText))
            {
                ProcessException.DisplayErrors(new Exception("Empty Command"));
            }
            try
            {
                cmdText = cmdText.TrimStart();

                cmdText = cmdText.TrimEnd();

                cmdText = cmdText.ToLower();

                if (cmdText.StartsWith("select"))
                {
                    _curCmdType = CurCommandType.Query;
                }
                else if (cmdText.StartsWith("insert"))
                {
                    _curCmdType = CurCommandType.Insert;
                }
                else if (cmdText.StartsWith("update"))
                {
                    _curCmdType = CurCommandType.Update;
                }
                else if (cmdText.StartsWith("delete"))
                {
                    _curCmdType = CurCommandType.Delete;
                }
                else if (cmdText.StartsWith("alter")||(cmdText.StartsWith("drop")))
                {
                    _curCmdType = CurCommandType.SystemAction;
                }
                else if (cmdText.StartsWith("create"))
                {
                    _curCmdType = CurCommandType.CreateTable;
                
                }
                else if (cmdText.StartsWith("sp_rename"))
                {
                    _curCmdType = CurCommandType.SpeicalCommand;
                }
                else
                {
                    _curCmdType = CurCommandType.Unknown;
                }

                result = cmdText;
            }
            catch (Exception ee)
            {
                ProcessException.DisplayErrors(ee);
            }

            return result;
        }


    }
}
